package com.zxy.config.realm;

import cn.hutool.core.bean.BeanUtil;
import com.zxy.config.shiro.AccountProfile;
import com.zxy.config.shiro.JwtToken;
import com.zxy.config.util.JwtUtils;
import com.zxy.entity.User;
import com.zxy.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

/**
 * @author: Zxy
 * @Date: 2021-04-15
 **/
@Component
@RequiredArgsConstructor
public class AccountRealm extends AuthorizingRealm {

    private final JwtUtils jwtUtils;

    private final UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("authenticationToken = " + authenticationToken);
        JwtToken token = (JwtToken) authenticationToken;
        String userId = jwtUtils.getClaimByToken((String) token.getPrincipal()).getSubject();
        User user = userService.getById(Long.valueOf(userId));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账户已被锁定");
        }
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        // 参数1：user对象 参数2：从数据库中拿到的密码 参数三：当前对象名   但是如果在使用时你写了四个参数，那么第三个参数就是你加密的盐值，第四个是当前对象名
        return new SimpleAuthenticationInfo(profile, token.getCredentials(), getName());
    }
}
